package com.system.honour.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @Description:    security配置类
 * @Author:         Joe
 * @CreateDate:     2020/4/4 13:33
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter{ //重写方法

	@Autowired
	private UserDetailsService userDetailsService; //用户校验接口
	@Autowired
	private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;
	@Autowired
	private MyAuthenticationFailureHandler myAuthenticationFailureHandler;
	@Autowired
	private RestAuthenticationAccessDeniedhandler restAuthenticationAccessDeniedhandler;
	@Autowired
	private MyLogoutSuccessHandler myLogoutSuccessHandler;
	/**
	 * 密码
	 * @return
	 */
	@Bean
	public PasswordEncoder passwordEncoder(){
		return new BCryptPasswordEncoder();
	}

	/**
	 * 身份验证管理生成器
	 * @param auth
	 * @throws Exception
	 */
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
	}

	/**
	 * http请求的安全处理
	 * @param http
	 * @throws Exception
	 */
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.csrf().disable(); 	//关闭自带的身份请求拦截
		http.headers().frameOptions().sameOrigin();//释放部分资源
		http.authorizeRequests() // 开始请求权限配置
				.antMatchers("/static/**","/layui/**")  //不需要认证的资源(静态资源等)不会被拦截
				.permitAll()    //前面的都是默认被允许请求的
				.anyRequest()	//任何请求
		.authenticated();		//任何请求都需要认证

		//自定义指向的登录页面
		http.formLogin()
				.loginPage("/login.html")		//具体页面
				.loginProcessingUrl("/login")	//请求拦截url
				.successHandler(myAuthenticationSuccessHandler)  //登录成功
				.failureHandler(myAuthenticationFailureHandler)  //登录失败
		//登出功能
		.and().logout()
				.permitAll()
				.invalidateHttpSession(true) //session失效
				.deleteCookies("JSESSIONID") //删除cookies
				.logoutSuccessHandler(myLogoutSuccessHandler);

		//异常处理
		http.exceptionHandling().accessDeniedHandler(restAuthenticationAccessDeniedhandler);
	}
}
